package com.wh.minihelp.user.dao;

import java.util.Date;
import java.util.List;
import java.util.Random;

import com.wh.db.jdbc.mysql.BaseJDBCDao;
import com.wh.db.sql.SQLUtils;
import com.wh.lang.LogicException;
import com.wh.minihelp.flower.dao.FlowerDBMetas;
import com.wh.minihelp.flower.domain.ChildFlower;
import com.wh.minihelp.user.dao.UserDBMetas.AccountInfoMapper;
import com.wh.minihelp.user.dao.UserDBMetas.AccountInfoSetter;
import com.wh.minihelp.user.dao.UserDBMetas.AccountInfoUpdater;
import com.wh.minihelp.user.dao.UserDBMetas.ChildInfoSetter;
import com.wh.minihelp.user.dao.UserDBMetas.ChildNameUpdateSetter;
import com.wh.minihelp.user.dao.UserDBMetas.FamilyAccountAllMapper;
import com.wh.minihelp.user.dao.UserDBMetas.FamilyAccountSetter;
import com.wh.minihelp.user.dao.UserDBMetas.FamilyChildMapper;
import com.wh.minihelp.user.dao.UserDBMetas.FamilyInfoMapper;
import com.wh.minihelp.user.dao.UserDBMetas.FamilyInfoSetter;
import com.wh.minihelp.user.domain.AccountInfo;
import com.wh.minihelp.user.domain.ChildInfo;
import com.wh.minihelp.user.domain.FamilyAccount;
import com.wh.minihelp.user.domain.FamilyInfo;
import com.wh.minihelp.user.util.UserUtil;

public class UserDao extends BaseJDBCDao {

	public UserDao() {}

	public FamilyAccount getUserDefault(String accountId) {
		FamilyAccountAllMapper mapper = new FamilyAccountAllMapper();
		try {
			List<FamilyAccount> fas = ds.query(FamilyAccountAllMapper.sql_all //
					+ " and fa.t_type!=" + FamilyAccount.Deleted// 被删除的
					+ " and fa.t_isDefault=1"// 默认的
					+ " and a.id='" + SQLUtils.delSpecialSQLChar(accountId) + "'", mapper);
			if (fas.size() > 0) {
				return fas.get(0);
			}
			return null;
		} catch (Throwable e) {
			throw new LogicException("查询已加入的家庭信息失败。", e);
		}
	}

	public FamilyAccount getFamilyAccount(String accountId, String familyId) {
		FamilyAccountAllMapper mapper = new FamilyAccountAllMapper();
		try {
			List<FamilyAccount> fas = ds.query(FamilyAccountAllMapper.sql_all //
					// + " and fa.t_type!=" + FamilyAccount.Deleted// 被删除的在这里也需要查出来，否则再次添加时可能会造成重复数据
					+ " and f.id='" + SQLUtils.delSpecialSQLChar(familyId) + "'"// 默认的
					+ " and a.id='" + SQLUtils.delSpecialSQLChar(accountId) + "'", mapper);
			return fas.size() > 0 ? fas.get(0) : null;
		} catch (Throwable e) {
			throw new LogicException("查询已加入的家庭信息失败。", e);
		}
	}

	// 获取帐号对应的家庭信息
	public List<FamilyAccount> getAccountFamilies(String accountId) {
		FamilyAccountAllMapper mapper = new FamilyAccountAllMapper();
		try {
			return ds.query(FamilyAccountAllMapper.sql_all //
					+ " and fa.t_type!=" + FamilyAccount.Deleted// 被删除的
					+ " and a.id='" + SQLUtils.delSpecialSQLChar(accountId) + "'", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询已加入的家庭信息失败。", e);
		}
	}

	public List<FamilyAccount> getFamilyMemebers(String familyId) {
		FamilyAccountAllMapper mapper = new FamilyAccountAllMapper();
		try {
			return ds.query(FamilyAccountAllMapper.sql_all //
					+ " and fa.t_type!=" + FamilyAccount.Deleted // 没有被删除的
					+ " and f.id='" + SQLUtils.delSpecialSQLChar(familyId) + "'", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询当前家庭的成员信息失败。", e);
		}
	}

	// 通过微信id来获取注册用户
	public AccountInfo getAccountByWX(String wxId) {
		AccountInfoMapper mapper = new AccountInfoMapper();//
		try {
			return ds.queryForObject(AccountInfoMapper.sql_all + " where id='" + SQLUtils.delSpecialSQLChar(wxId) + "'", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询用户信息失败", e);
		}
	}

	// 通过家庭名称查询家庭，一般用于在创建家庭时，检查家庭是否存在
	public FamilyInfo getFamilyByName(String familyName) {
		FamilyInfoMapper mapper = new FamilyInfoMapper();//
		try {
			return ds.queryForObject(FamilyInfoMapper.sql_all + " where t_name='" + SQLUtils.delSpecialSQLChar(familyName) + "'", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询家庭信息失败", e);
		}
	}

	// 通过帐号获取关联的小孩
	public List<ChildInfo> getChilds(FamilyAccount account) {
		FamilyChildMapper mapper = new FamilyChildMapper();
		try {
			return ds.query(FamilyChildMapper.sql_all //
					+ " where t_familyId='" + account.getFamilyId() + "'"//
					+" order by t_createDate desc", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询小孩信息失败。", e);
		}
	}

	// 根据小孩id获取小孩与家庭的关联
	public ChildInfo getFamilyChild(String childId) {
		FamilyChildMapper mapper = new FamilyChildMapper();
		try {
			return ds.queryForObject(FamilyChildMapper.sql_all + " where id='" + SQLUtils.delSpecialSQLChar(childId) + "'", mapper);
		} catch (Throwable e) {
			throw new LogicException("查询小孩信息失败。", e);
		}
	}

	// 创建帐号
	public FamilyAccount createAccount(AccountInfo acc, FamilyInfo family, int type, boolean saveFamily, boolean saveAccount, boolean asDefault) {
		FamilyAccount fa = getFamilyAccount(acc.getId(), family.getId());
		boolean newer = false;
		if (fa == null) {
			newer = true;
			fa = new FamilyAccount();
			fa.setAccount(acc);
			fa.setAccountId(acc.getId());
			fa.setCreateDate(new Date());
			fa.setFamily(family);
			fa.setFamilyId(family.getId());
			fa.setDefault(asDefault);
		} else {
			fa.setDefault(false);
		}
		fa.setType(type);
		try {
			if (saveAccount) ds.save(AccountInfoSetter.SQL_INSERT, acc, new AccountInfoSetter());// 帐号
			if (newer) {
				ds.save(FamilyAccountSetter.SQL_INSERT, fa, new FamilyAccountSetter());// 关联家庭与帐号
			} else {
				String sql = "update " + UserDBMetas.TN_FamilyAccount + " set t_type=" + fa.getType()//
						+ " where t_accountId='" + fa.getAccountId() + "' and t_familyId='" + fa.getFamilyId() + "'";
				ds.execute(sql);// 设置
			}
			if (saveFamily) ds.save(FamilyInfoSetter.SQL_INSERT, family, new FamilyInfoSetter());// 家庭
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("创建帐号信息失败。", e);
		}
		return fa;
	}

	public void setUserType(FamilyAccount fa) {
		try {
			String sql = "update " + UserDBMetas.TN_FamilyAccount + " set t_type=" + fa.getType()//
					+ " where t_accountId='" + fa.getAccountId() + "' and t_familyId='" + fa.getFamilyId() + "'";
			ds.execute(sql);
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("设置帐号类别失败。", e);
		}
	}

	public void changeDefaultFamily(String accountId, String fid) {
		try {
			String sql = "update " + UserDBMetas.TN_FamilyAccount + " set t_isDefault=0" //
					+ " where t_isDefault=1 and t_accountId='" + accountId + "';";// 将原来的默认去掉
			ds.execute(sql);
			sql = "update " + UserDBMetas.TN_FamilyAccount + " set t_isDefault=1" //
					+ " where t_accountId='" + accountId + "' and t_familyId='" + fid + "'";
			ds.execute(sql);
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("设置帐号与家庭关系失败。", e);
		}
	}

	public void delFamilyAccount(FamilyAccount fa) {
		try {
			// String sql = "select count(*) from " + UserDBMetas.TN_ChildFLower //
			// + " where t_operAcount='" + SQLUtils.delSpecialSQLChar(fa.getAccountId()) + "'"//
			// + " and t_childId in (select id from " + UserDBMetas.TN_ChildInfo + "where t_familyId='" + SQLUtils.delSpecialSQLChar(fa.getFamilyId()) + "')";
			// Number number = ds.queryForObject(sql);
			// if (number.intValue() > 0) {// 在此家庭有记录红花信息，那么将其设置为删除类型，而不是直接删除关联关系
			//// 还是保留此关系吧，以便让人看到是被请离的
			// }
			fa.setType(FamilyAccount.Deleted);
			setUserType(fa);
		} catch (Throwable e) {
			throw new LogicException("处理家庭成员信息失败。", e);
		}
	}

	public void createFamilyChild(ChildInfo fc) {
		try {
			ds.save(ChildInfoSetter.SQL_INSERT, fc, new ChildInfoSetter());// 小孩
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("保存小孩信息失败。", e);
		}
	}

	public void updateFamilyChild(ChildInfo fc) {
		try {
			ds.save(ChildNameUpdateSetter.SQL_UPDATE_NAME, fc, new ChildNameUpdateSetter());// 小孩
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("更新小孩名称失败。", e);
		}
	}

	public void deleteChild(String id) {
		String sql = "delete from " + UserDBMetas.TN_ChildInfo + " where id='" + SQLUtils.delSpecialSQLChar(id) + "'";
		try {
			ds.execute(sql);
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("删除小孩信息失败。", e);
		}
	}

	public int getChildFlowerRecordCount(String id) {
		String sql = "select count(*) from " + FlowerDBMetas.TN_ChildFLower //
				+ " where t_childId='" + SQLUtils.delSpecialSQLChar(id) + "'"//
		;
		try {
			Number number = ds.queryForObject(sql);
			return number.intValue();
		} catch (Throwable e) {
			throw new LogicException("获取小孩红花记录次数失败。", e);
		}
	}

	public String resetUserPassword(String wxId) {
		AccountInfo user = getAccountByWX(wxId);
		if (user == null) return null;
		String pwd = UserUtil.genPwd(4);
		user.setPwd(pwd);
		updateUser(user);
		return pwd;
	}

	public void updateUser(AccountInfo accountInfo) {
		try {
			ds.save(AccountInfoUpdater.SQL_UPDATE, accountInfo, new AccountInfoUpdater());// 小孩
			ds.saveOrUpdateAll();
		} catch (Throwable e) {
			throw new LogicException("更新小孩名称失败。", e);
		}
	}
}